package com.tanhua.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.admin.service.AdminService;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AdminMapper adminMapper;

//    用户登录验证码图片
//    GET   /system/users/verification
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(300, 100);
        String code = circleCaptcha.getCode();
        redisTemplate.opsForValue().set(Constants.CAP_CODE+uuid,code, Duration.ofMinutes(5));
        circleCaptcha.write(response.getOutputStream());
    }

//    用户登录
//    POST  /system/users/login
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
//        Map retMap = adminService.login(map);
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class)
                .eq(Admin::getUsername, username));
        Map<String,Object> params = new HashMap<>();
        params.put("id",admin.getId());
        params.put("username",admin.getUsername());
        String token = JwtUtils.getToken(params);
        Map result = new HashMap<>();
        result.put("token",token);
        return ResponseEntity.ok(result);
    }

//    获取管理员信息
//    POST  /system/users/profile
    @PostMapping("/profile")
    public ResponseEntity profile(){
        AdminVo vo = adminService.profile();
        return ResponseEntity.ok(vo);
    }

//    用户登出
//    POST  /system/users/logout
    @PostMapping("/logout")
    public ResponseEntity logout() {
        return ResponseEntity.ok(null);
    }

}
